<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 150px;
            height: 150px;
            background-color: skyblue;
            position: absolute;
            left: 0;
            top: 0;
            /* z-index: ; */
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <script>
        var box = document.querySelectorAll(".box")
        function DragEle(ele) {
            var obj = {
                // target: ele,
                dragStar() {
                    var _this = this
                    ele.onmousedown = function (e) {
                        var e = e || window.event;
                        var posx = e.offsetX;
                        var posY = e.offsetY;
                        _this.posx = posx;
                        _this.posY = posY;
                        ele.style.zIndex = 999
                        obj.dragmove();
                        obj.dragend();

                    }

                },
                dragmove() {
                    document.onmousemove = (e) => {
                        var e = e || window.event
                        ele.style.left = (e.pageX - this.posx) + "px";
                        ele.style.top = (e.pageY - this.posY) + "px";
                    }
                },
                dragend() {
                    document.onmouseup = function () {
                        document.onmousemove = null;
                        // ele.onmousedown = null;
                        // document.onmouseup = null;
                        ele.style.zIndex = "auto";
                    }
                },
                dragColor() {
                    var str = "0123456789abcdef"
                    var color = "#"
                    for (var i = 0; i < 6; i++) {
                        var index = Math.floor(Math.random() * str.length)
                        color += str.charAt(index)
                    }
                    console.log(color);
                    ele.style.backgroundColor = color
                }
            }

            obj.dragStar()
            obj.dragColor()
        }
        for (var i = 0; i < box.length; i++) {
            var list = box[i]
            DragEle(list);
        }

    </script>
</body>

</html>